package com.education.upload.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QiniuUtil {

    //设置好账号的ACCESS_KEY和SECRET_KEY
    static final String ACCESS_KEY = "TWDj6oF-ZkhXLmn8Iipc0woi6teoq-jerUpwuW3s";
    static final String SECRET_KEY = "S6FGTu-FfkSIoii0k9jUwRz2S5Xlac7VhVl_cELy";

    /**
     * 要上传的空间对应的 urlPrefix scheme + host
     * host:
     * 华东机房(region0): up.qiniup.com 或 upload.qiniup.com
     * 华北机房(region1): up-z1.qiniup.com 或 upload-z1.qiniup.com
     * 华南机房(region2): up-z2.qiniup.com 或 upload-z2.qiniup.com
     * 北美机房(regionNa0): up-na0.qiniup.com 或 upload-na0.qiniup.com
     * 新加坡机房(regionAs0): up-as0.qiniup.com 或 upload-as0.qiniup.com
     * 雾存储华东一区(regionFogCnEast1): up-fog-cn-east-1.qiniup.com 或 upload-fog-cn-east-1.qiniup.com
     */
    static final String URLPREFIX = "http://upload.qiniup.com"; // http://up.qiniup.com";

    static final String BUCKET_NAME = "reource";
    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    private String getUpToken() {
        return auth.uploadToken(BUCKET_NAME);
    }

    /**
     * 1.获取uploadId
     *
     * @param key
     * @return
     */
    public String initiateMultipartUpload(String key) throws Exception {
        String token = getUpToken();

        Configuration configuration = new Configuration();
        Client client = new Client(configuration);

        // 1. init upload
        String uploadId = null;
        ApiUploadV2InitUpload initUploadApi = new ApiUploadV2InitUpload(client);
        ApiUploadV2InitUpload.Request initUploadRequest = new ApiUploadV2InitUpload.Request(URLPREFIX, token)
                .setKey(key);
        try {
            ApiUploadV2InitUpload.Response initUploadResponse = initUploadApi.request(initUploadRequest);
            uploadId = initUploadResponse.getUploadId();
            System.out.println("init upload:" + initUploadResponse.getResponse());
            System.out.println("init upload id::" + initUploadResponse.getUploadId());
        } catch (
                QiniuException e) {
            e.printStackTrace();
            throw e;
        }
        return uploadId;
    }


    /**
     * 2. 上传文件数据
     *
     * @param uploadId   从七牛云获取的唯一id
     * @param key        文件名称
     * @param partNumber part num 从 1 开始
     * @param partData   分片数据
     */
    public Map<String, Object> uploadPart(String uploadId, String key, int partNumber, byte[] partData) throws Exception {

        Map<String, Object> partInfo = new HashMap<>();
        String token = getUpToken();
        Configuration configuration = new Configuration();
        Client client = new Client(configuration);

        // 1.2.2 上传 part 数据
        ApiUploadV2UploadPart uploadPartApi = new ApiUploadV2UploadPart(client);
        ApiUploadV2UploadPart.Request uploadPartRequest = new ApiUploadV2UploadPart.Request(URLPREFIX, token, uploadId, partNumber)
                .setKey(key)
                .setUploadData(partData, 0, partData.length, null);
        try {
            ApiUploadV2UploadPart.Response uploadPartResponse = uploadPartApi.request(uploadPartRequest);
            String etag = uploadPartResponse.getEtag();
            String md5 = uploadPartResponse.getMd5();
            partInfo.put(ApiUploadV2CompleteUpload.Request.PART_NUMBER, partNumber);
            partInfo.put(ApiUploadV2CompleteUpload.Request.PART_ETG, etag);
            System.out.println("upload part:" + uploadPartResponse.getResponse());
        } catch (QiniuException e) {
            e.printStackTrace();
            throw e;
        }
        return partInfo;
    }

    /**
     * 3.组装文件
     *
     * @param uploadId  从七牛云获取的唯一id
     * @param key       文件名称
     * @param partsInfo
     */
    public boolean completeMultipartUpload(String uploadId, String key, String fileName,
                                           List<Map<String, Object>> partsInfo) throws Exception {
        String token = getUpToken();
        Configuration configuration = new Configuration();
        Client client = new Client(configuration);

        String fooKey = "foo";
        String fooValue = "foo-Value";
        Map<String, Object> customParam = new HashMap<>();
        customParam.put("x:foo", fooValue);
        ApiUploadV2CompleteUpload completeUploadApi = new ApiUploadV2CompleteUpload(client);
        ApiUploadV2CompleteUpload.Request completeUploadRequest = new ApiUploadV2CompleteUpload.Request(URLPREFIX, token, uploadId, partsInfo)
                .setKey(key)
                .setFileName(fileName)
                .setCustomParam(customParam);
        try {
            ApiUploadV2CompleteUpload.Response completeUploadResponse = completeUploadApi.request(completeUploadRequest);
            DefaultPutRet putRet = new Gson().fromJson(completeUploadResponse.getResponse().bodyString(), DefaultPutRet.class);
            if (putRet == null || StringUtils.isBlank(putRet.key)) {
                return false;
            }
            System.out.println("complete upload:" + completeUploadResponse.getResponse());
            System.out.println("complete upload:" + putRet);
        } catch (QiniuException e) {
            e.printStackTrace();
            throw e;
        }
        return true;
    }


    /**
     * 生成文件名称
     *
     * @return
     */
    public static String getFileName(MultipartFile file) {
        String suffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        String time = DateUtils.dateTimeNow();
        StringBuilder builder = new StringBuilder();
        return builder.append(time).append(UUIDUtils.getByUUId()).append(".").append(suffix).toString();
    }


    public static void main(String args[]) {
        download();
    }

    public static void download() {
        //密钥配置
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        //构造私有空间的需要生成的下载的链接
//        String URL = "http://bucketdomain/key";
        String URL = "http://upload.qiniup.com/reource/8888";
        //调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间
        String downloadRUL = auth.privateDownloadUrl(URL, 3600);
        System.out.println(downloadRUL);
    }

    /**
     * MultipartFile 转 File
     *
     * @param multipartFile
     * @throws Exception
     */
    public static File MultipartFileToFile(MultipartFile multipartFile) {

        File file = null;
        //判断是否为null
        if (multipartFile.equals("") || multipartFile.getSize() <= 0) {
            return file;
        }
        //MultipartFile转换为File
        InputStream ins = null;
        OutputStream os = null;
        try {
            ins = multipartFile.getInputStream();
            file = new File(multipartFile.getOriginalFilename());
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


}
